package com.card.hwatt.assembler;

import java.util.ArrayList;
import java.util.List;

import com.card.hwatt.core.ObjectUtil;
import com.card.hwatt.dto.TreeEntity;
import com.card.hwatt.entity.Department;

/**
 * 单位
 * @author Administrator
 *
 */
public final class DepartmentAssembler {

	public static List<com.card.hwatt.dto.Department> convert(
			List<Department> list) {
		List<com.card.hwatt.dto.Department> rows = new ArrayList<com.card.hwatt.dto.Department>();
		for (Department item : list) {
			com.card.hwatt.dto.Department dto = convert(item);
			rows.add(dto);
		}
		return rows;
	}

	public static List<TreeEntity> convertTree(List<Department> list) {
		List<TreeEntity> tree = new ArrayList<TreeEntity>();
		List<com.card.hwatt.dto.Department> src = convert(list);
		fillTree(tree, src, 0L);
		return tree;
	}

	private static void fillTree(List<TreeEntity> list,
			List<com.card.hwatt.dto.Department> src, Long parentId) {
		if (src == null) {
			return;
		}

		for (com.card.hwatt.dto.Department item : src) {
			if ((parentId == null && item.parentId == null)
					|| (parentId == 0 && item.parentId == 0)
					|| (parentId != null && item.parentId != null && parentId == item.parentId)) {

				TreeEntity node = new TreeEntity();
				node.id = item.id;
				node.name = item.name;
				node.children = new ArrayList<TreeEntity>();
				list.add(node);

				fillTree(node.children, src, item.id);
			}
		}
	}

	public static com.card.hwatt.dto.Department convert(Department entity) {
		if (entity == null) {
			return null;
		}
		com.card.hwatt.dto.Department dto = new com.card.hwatt.dto.Department();
		ObjectUtil.fieldCopy(entity, dto);
		return dto;
	}

	public static Department convert(com.card.hwatt.dto.Department dto) {
		Department entity = new Department();
		ObjectUtil.fieldCopy(dto, entity);
		return entity;
	}
}
